import axios, { type AxiosRequestConfig } from 'axios'

console.log('process.env.VITE_APP_BASE_URL', process.env.VITE_APP_BASE_URL)

export const instance = axios.create({
  baseURL: process.env.VITE_APP_BASE_URL,
  timeout: 1000
})

// 请求拦截
instance.interceptors.request.use(
  config => {
    return config
  },
  async error => {
    return await Promise.reject(error)
  }
)

// 响应拦截
instance.interceptors.response.use(
  response => {
    return response
  },
  async error => {
    return await Promise.reject(error)
  }
)

type Fn = <T>(data: FcResponse<T>) => unknown

interface FcResponse<T> {
  data: T
}

export const request = async <T>(
  config: AxiosRequestConfig,
  callback?: Fn
): Promise<[unknown, FcResponse<T> | null]> => {
  return await new Promise(resolve => {
    instance(config)
      .then(result => {
        const res: FcResponse<T> =
          callback != null
            ? (callback(result.data) as FcResponse<T>)
            : (result.data as FcResponse<T>)
        resolve([null, res])
      })
      .catch(err => {
        resolve([err, null])
      })
  })
}
